// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.DataIndex;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.PageSearchFilter;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.AdjustmentOrder;
import com.fowo.api.entity.AdjustmentOrderProduct;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.inventory.model.InventoryExchangeVo;
import com.fowo.api.inventory.model.InventoryOutboundVo;
import com.fowo.api.inventory.model.InventoryStorageVo;
import com.fowo.api.inventory.model.PatternEnum;
import com.fowo.api.inventory.model.SimpleInventoryItem;
import com.fowo.api.inventory.model.TargetTypeEnum;
import com.fowo.api.inventory.model.form.InventoryExchangeFormVo;
import com.fowo.api.inventory.model.form.InventoryOutboundFormVo;
import com.fowo.api.inventory.model.form.InventoryStorageFormVo;
import com.fowo.api.inventory.service.InventoryBusinessService;
import com.fowo.api.mapper.AdjustmentOrderMapper;
import com.fowo.api.mapper.AdjustmentOrderProductMapper;
import com.fowo.api.mapper.InventoryPlacementRMapper;
import com.fowo.api.mapper.ListingFatherMapper;
import com.fowo.api.mapper.ProductMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.WarehouseBinMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.adjustment.order.AdjustmentOrderAndAdjustmentOrderProductImportPo;
import com.fowo.api.model.adjustment.order.AdjustmentOrderDataFiltrationParam;
import com.fowo.api.model.adjustment.order.AdjustmentOrderDataFiltrationResult;
import com.fowo.api.model.adjustment.order.AdjustmentOrderExcelPo;
import com.fowo.api.model.adjustment.order.AdjustmentOrderImportPo;
import com.fowo.api.model.adjustment.order.AdjustmentOrderItemVo;
import com.fowo.api.model.adjustment.order.AdjustmentOrderSearchParamPo;
import com.fowo.api.model.adjustment.order.AdjustmentOrderSyncDataAction;
import com.fowo.api.model.adjustment.order.AdjustmentOrderVo;
import com.fowo.api.model.adjustment.order.constant.AdjustmentOrderTypeEnums;
import com.fowo.api.model.adjustment.order.product.AdjustmentOrderProductItemVo;
import com.fowo.api.model.adjustment.order.product.AdjustmentOrderProductItemVoPages;
import com.fowo.api.model.adjustment.order.product.AdjustmentOrderProductSearchParamPo;
import com.fowo.api.model.inventory.placement.r.InventoryPlacementRItemVo;
import com.fowo.api.model.inventory.placement.r.InventoryPlacementRSearchParamPo;
import com.fowo.api.model.listing.father.ListingFatherItemVo;
import com.fowo.api.model.listing.father.ListingFatherSearchParamPo;
import com.fowo.api.model.product.ProductItemVo;
import com.fowo.api.model.product.ProductSearchParamPo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.model.warehouse.bin.WarehouseBinItemVo;
import com.fowo.api.model.warehouse.bin.WarehouseBinSearchParamPo;
import com.fowo.api.service.AdjustmentOrderProductService;
import com.fowo.api.service.AdjustmentOrderService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 调整单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：陈新新，吕家傲
 */
@Slf4j
@DataObjectType(AdjustmentOrder.class)
@DS("ds24")
public class AdjustmentOrderBaseServiceImpl
  extends ServiceImpl<AdjustmentOrderMapper, AdjustmentOrder>
  implements AdjustmentOrderService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("widName", "w.`name`");
      put("createUserName", "su.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected AdjustmentOrderService self;

  @Resource
  protected AdjustmentOrderProductService adjustmentOrderProductService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  private AdjustmentOrderProductMapper childMapper;

  @Resource
  protected ProductMapper productMapper;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected ListingFatherMapper listingFatherMapper;

  @Resource
  protected WarehouseBinMapper warehouseBinMapper;

  @Resource
  protected InventoryPlacementRMapper inventoryPlacementRMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Resource
  protected InventoryBusinessService inventoryBusinessService;

  @Autowired(required = false)
  protected AdjustmentOrderSyncDataAction adjustmentOrderSyncDataAction;

  @Resource
  protected Validator validator;

  /**
   * 创建调整单
   * @param model 调整单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(AdjustmentOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    AdjustmentOrder entity = new AdjustmentOrder();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getStatus() == null) {
      entity.setStatus("5");
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getOrderSn())) {
      entity.setOrderSn(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "AdjustmentOrder.orderSn")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("调整单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 调整单
   */
  protected void updateAllChilds(AdjustmentOrderVo model) throws Exception {
    if (model.getProductLists() != null) {
      adjustmentOrderProductService.saveAllByParentAdjustmentOrder(
        model.getId(),
        model.getProductLists()
      );
    }
  }

  /**
   * 更新调整单
   * @param model 调整单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(AdjustmentOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    AdjustmentOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("调整单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "lastUpdateTime",
      "lastUpdateUser",
      "createUser",
      "createTime"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新调整单（带空值）
   * @param model 调整单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(AdjustmentOrderVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    AdjustmentOrder entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("调整单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(AdjustmentOrder::getLastUpdateTime, model.getLastUpdateTime())
      .set(AdjustmentOrder::getLastUpdateUser, model.getLastUpdateUser())
      .set(AdjustmentOrder::getWid, model.getWid())
      .set(AdjustmentOrder::getType, model.getType())
      .set(
        model.getFiles() != null,
        AdjustmentOrder::getFiles,
        JSON.toJSONString(model.getFiles())
      )
      .setSql(model.getFiles() == null, "files = null")
      .set(AdjustmentOrder::getRemark, model.getRemark())
      .eq(AdjustmentOrder::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(AdjustmentOrderSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 调整单子表(productLists) 对应的对象
    AdjustmentOrderProductSearchParamPo productListsSearchParam =
      new AdjustmentOrderProductSearchParamPo();
    productListsSearchParam.setDisableDataPremissions(true);
    productListsSearchParam.setParentAdjustmentOrderInList(ids);
    AdjustmentOrderProductMapper localAdjustmentOrderProductMapper =
      ContextHolder
        .getApplicationContext()
        .getBean(AdjustmentOrderProductMapper.class);
    productListsSearchParam.applySqlSegments();
    List<Long> productListsIdList = localAdjustmentOrderProductMapper.searchIds(
      productListsSearchParam
    );
    if (!productListsIdList.isEmpty()) {
      AdjustmentOrderProductService localAdjustmentOrderProductService =
        ContextHolder
          .getApplicationContext()
          .getBean(AdjustmentOrderProductService.class);
      localAdjustmentOrderProductService.batchDelete(productListsIdList);
    }
  }

  /**
   * 删除调整单
   * @param id 调整单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除调整单
   * @param ids 调整单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<AdjustmentOrderImportPo> excelToImportRow(
    AdjustmentOrderImportPo row,
    Integer rowNumber,
    AdjustmentOrderVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<AdjustmentOrderImportPo> ir =
      new ImportRow<AdjustmentOrderImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<AdjustmentOrderImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new AdjustmentOrderVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, AdjustmentOrderImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getType())) {
      vo.setType(AdjustmentOrderTypeEnums.toValue(row.getType()));
      if (vo.getType() == null) {
        ir.addError("type", "类型只能是：“数量调整”, “换标调整”, “SKU调整”");
      }
    }
    if (StringUtils.hasText(row.getStatus())) {
      List<SysDictAllItem> statusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "status",
          n -> sysDictService.getDictItems("SCM00078")
        );
      AdjustmentOrderVo finalVo = vo;
      statusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setStatus(i.getItemValue()),
          () ->
            ir.addError(
              "status",
              String.format(
                "必须为 %s 中之一",
                statusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    // 处理关联字段“仓库”
    if (
      !SheetUtils.isBlank(row.getWidName()) && SheetUtils.isBlank(row.getWid())
    ) {
      WarehouseSearchParamPo widSearchParam = new WarehouseSearchParamPo();
      widSearchParam.setLimit(2); // 最大只返回二行记录
      widSearchParam.setNameEq(SheetUtils.trim(row.getWidName()));
      widSearchParam.setFinalFilters(new ArrayList<>());
      widSearchParam
        .getFinalFilters()
        .add(
          new PageSearchFilter()
            .setDataIndex(new DataIndex("widType"))
            .setOp("eq")
            .setValue("1")
        );
      widSearchParam.applySqlSegments();
      List<WarehouseItemVo> widMatches = warehouseMapper.search(widSearchParam);
      if (widMatches.size() == 0) {
        ir.addError("widName", "未能在仓库即时库存中找到匹配的数据");
      } else if (widMatches.size() > 1) {
        ir.addError(
          "widName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setWid(widMatches.get(0).getId());
      }
    }
    // 子表导入处理
    if (row.getProductLists() != null && !row.getProductLists().isEmpty()) {
      List<ImportRow<AdjustmentOrderAndAdjustmentOrderProductImportPo>> handledChildRows =
        new ArrayList<>();
      AdjustmentOrderProductItemVo childVo = new AdjustmentOrderProductItemVo();
      for (ImportRow<AdjustmentOrderAndAdjustmentOrderProductImportPo> childRowPo : row.getProductLists()) {
        final ImportRow<AdjustmentOrderAndAdjustmentOrderProductImportPo> childImportRow =
          excelToImportChildRow(
            ir,
            childRowPo.getRow(),
            childRowPo.getRowNumber(),
            vo,
            childVo,
            variables
          );
        handledChildRows.add(childImportRow);
      }
      row.setProductLists(handledChildRows);
    }

    return ir;
  }

  /**
   * 子表导入处理
   */
  protected ImportRow<AdjustmentOrderAndAdjustmentOrderProductImportPo> excelToImportChildRow(
    ImportRow<AdjustmentOrderImportPo> parentRow,
    AdjustmentOrderAndAdjustmentOrderProductImportPo row,
    Integer rowNumber,
    AdjustmentOrderVo parentVo,
    AdjustmentOrderProductItemVo vo,
    Map<String, Object> variables
  ) {
    ImportRow<AdjustmentOrderAndAdjustmentOrderProductImportPo> ir =
      new ImportRow<>();
    ir.setParentRowNumber(parentRow.getRowNumber());
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<AdjustmentOrderAndAdjustmentOrderProductImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new AdjustmentOrderProductItemVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(
      validate,
      AdjustmentOrderAndAdjustmentOrderProductImportPo.class
    );

    // 一般数据处理
    vo.setAvailbleNum(SheetUtils.tryToLong(row.getAvailbleNum()));
    vo.setNewAvailbleNum(SheetUtils.tryToLong(row.getNewAvailbleNum()));
    vo.setGoodAdjustNum(SheetUtils.tryToLong(row.getGoodAdjustNum()));
    vo.setDefectiveQuantity(SheetUtils.tryToLong(row.getDefectiveQuantity()));
    vo.setBadAdjustNum(SheetUtils.tryToLong(row.getBadAdjustNum()));
    vo.setAdjustmentAmount(SheetUtils.tryToLong(row.getAdjustmentAmount()));
    // 处理关联字段“品名”
    if (
      !SheetUtils.isBlank(row.getPrdNameName()) &&
      SheetUtils.isBlank(row.getPrdName())
    ) {
      ProductSearchParamPo prdNameSearchParam = new ProductSearchParamPo();
      prdNameSearchParam.setLimit(2); // 最大只返回二行记录
      prdNameSearchParam.setNameEq(SheetUtils.trim(row.getPrdNameName()));
      prdNameSearchParam.applySqlSegments();
      List<ProductItemVo> prdNameMatches = productMapper.search(
        prdNameSearchParam
      );
      if (prdNameMatches.size() == 0) {
        ir.addError("prdNameName", "未能在产品管理中找到匹配的数据");
      } else if (prdNameMatches.size() > 1) {
        ir.addError(
          "prdNameName",
          "关联不唯一，在产品管理中找到多个匹配的数据"
        );
      } else {
        vo.setPrdName(prdNameMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", prdNameMatches.get(0).getId())
          .put("fromObjectName", "AdjustmentOrder")
          .put("fromObjectId", vo.getId())
          .put("fromField", "prdName")
          .put("fromParentObjectName", "prdName")
          .put("fromParentObjectId", parentVo.getId())
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(2);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("sku")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("sku")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("sku")
              .rowFieldName("sku")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("prdLabel")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("label")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("prdLabel")
              .rowFieldName("prdLabel")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          parentRow,
          ir,
          parentVo,
          vo,
          CollUtil.getFirst(prdNameMatches),
          joinModels
        );
      }
    }
    // 处理关联字段“店铺”
    if (
      !SheetUtils.isBlank(row.getShopShopName()) &&
      SheetUtils.isBlank(row.getShop())
    ) {
      ShopInfoSearchParamPo shopSearchParam = new ShopInfoSearchParamPo();
      shopSearchParam.setLimit(2); // 最大只返回二行记录
      shopSearchParam.setShopNameEq(SheetUtils.trim(row.getShopShopName()));
      shopSearchParam.applySqlSegments();
      List<ShopInfoItemVo> shopMatches = shopInfoMapper.search(shopSearchParam);
      if (shopMatches.size() == 0) {
        ir.addError("shopShopName", "未能在店铺中找到匹配的数据");
      } else if (shopMatches.size() > 1) {
        ir.addError("shopShopName", "关联不唯一，在店铺中找到多个匹配的数据");
      } else {
        vo.setShop(shopMatches.get(0).getId());
      }
    }
    // 处理关联字段“FNSKU”
    if (
      !SheetUtils.isBlank(row.getFnskuFnsku()) &&
      SheetUtils.isBlank(row.getFnsku())
    ) {
      ListingFatherSearchParamPo fnskuSearchParam =
        new ListingFatherSearchParamPo();
      fnskuSearchParam.setLimit(2); // 最大只返回二行记录
      fnskuSearchParam.setFnskuEq(SheetUtils.trim(row.getFnskuFnsku()));
      fnskuSearchParam.applySqlSegments();
      List<ListingFatherItemVo> fnskuMatches = listingFatherMapper.search(
        fnskuSearchParam
      );
      if (fnskuMatches.size() == 0) {
        ir.addError("fnskuFnsku", "未能在Listing中找到匹配的数据");
      } else if (fnskuMatches.size() > 1) {
        ir.addError("fnskuFnsku", "关联不唯一，在Listing中找到多个匹配的数据");
      } else {
        vo.setFnsku(fnskuMatches.get(0).getId());
      }
    }
    // 处理关联字段“新品名”
    if (
      !SheetUtils.isBlank(row.getNewPrdNameName()) &&
      SheetUtils.isBlank(row.getNewPrdName())
    ) {
      ProductSearchParamPo newPrdNameSearchParam = new ProductSearchParamPo();
      newPrdNameSearchParam.setLimit(2); // 最大只返回二行记录
      newPrdNameSearchParam.setNameEq(SheetUtils.trim(row.getNewPrdNameName()));
      newPrdNameSearchParam.applySqlSegments();
      List<ProductItemVo> newPrdNameMatches = productMapper.search(
        newPrdNameSearchParam
      );
      if (newPrdNameMatches.size() == 0) {
        ir.addError("newPrdNameName", "未能在产品管理中找到匹配的数据");
      } else if (newPrdNameMatches.size() > 1) {
        ir.addError(
          "newPrdNameName",
          "关联不唯一，在产品管理中找到多个匹配的数据"
        );
      } else {
        vo.setNewPrdName(newPrdNameMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", newPrdNameMatches.get(0).getId())
          .put("fromObjectName", "AdjustmentOrder")
          .put("fromObjectId", vo.getId())
          .put("fromField", "newPrdName")
          .put("fromParentObjectName", "newPrdName")
          .put("fromParentObjectId", parentVo.getId())
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(1);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("newSku")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("sku")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("newSku")
              .rowFieldName("newSku")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          parentRow,
          ir,
          parentVo,
          vo,
          CollUtil.getFirst(newPrdNameMatches),
          joinModels
        );
      }
    }
    // 处理关联字段“新店铺”
    if (
      !SheetUtils.isBlank(row.getNewShopShopName()) &&
      SheetUtils.isBlank(row.getNewShop())
    ) {
      ShopInfoSearchParamPo newShopSearchParam = new ShopInfoSearchParamPo();
      newShopSearchParam.setLimit(2); // 最大只返回二行记录
      newShopSearchParam.setShopNameEq(
        SheetUtils.trim(row.getNewShopShopName())
      );
      newShopSearchParam.applySqlSegments();
      List<ShopInfoItemVo> newShopMatches = shopInfoMapper.search(
        newShopSearchParam
      );
      if (newShopMatches.size() == 0) {
        ir.addError("newShopShopName", "未能在店铺中找到匹配的数据");
      } else if (newShopMatches.size() > 1) {
        ir.addError(
          "newShopShopName",
          "关联不唯一，在店铺中找到多个匹配的数据"
        );
      } else {
        vo.setNewShop(newShopMatches.get(0).getId());
      }
    }
    // 处理关联字段“新FNSKU”
    if (
      !SheetUtils.isBlank(row.getNewFnskuFnsku()) &&
      SheetUtils.isBlank(row.getNewFnsku())
    ) {
      ListingFatherSearchParamPo newFnskuSearchParam =
        new ListingFatherSearchParamPo();
      newFnskuSearchParam.setLimit(2); // 最大只返回二行记录
      newFnskuSearchParam.setFnskuEq(SheetUtils.trim(row.getNewFnskuFnsku()));
      newFnskuSearchParam.applySqlSegments();
      List<ListingFatherItemVo> newFnskuMatches = listingFatherMapper.search(
        newFnskuSearchParam
      );
      if (newFnskuMatches.size() == 0) {
        ir.addError("newFnskuFnsku", "未能在Listing中找到匹配的数据");
      } else if (newFnskuMatches.size() > 1) {
        ir.addError(
          "newFnskuFnsku",
          "关联不唯一，在Listing中找到多个匹配的数据"
        );
      } else {
        vo.setNewFnsku(newFnskuMatches.get(0).getId());
      }
    }
    // 处理关联字段“出库仓位”
    if (
      !SheetUtils.isBlank(row.getGoodWarehouseBinStorageBin()) &&
      SheetUtils.isBlank(row.getGoodWarehouseBin())
    ) {
      WarehouseBinSearchParamPo goodWarehouseBinSearchParam =
        new WarehouseBinSearchParamPo();
      goodWarehouseBinSearchParam.setLimit(2); // 最大只返回二行记录
      goodWarehouseBinSearchParam.setStorageBinEq(
        SheetUtils.trim(row.getGoodWarehouseBinStorageBin())
      );
      goodWarehouseBinSearchParam.applySqlSegments();
      List<WarehouseBinItemVo> goodWarehouseBinMatches =
        warehouseBinMapper.search(goodWarehouseBinSearchParam);
      if (goodWarehouseBinMatches.size() == 0) {
        ir.addError("goodWarehouseBinStorageBin", "未能在仓位中找到匹配的数据");
      } else if (goodWarehouseBinMatches.size() > 1) {
        ir.addError(
          "goodWarehouseBinStorageBin",
          "关联不唯一，在仓位中找到多个匹配的数据"
        );
      } else {
        vo.setGoodWarehouseBin(goodWarehouseBinMatches.get(0).getId());
      }
    }
    // 处理关联字段“次品仓位”
    if (
      !SheetUtils.isBlank(row.getBadWarehouseBinStorageBin()) &&
      SheetUtils.isBlank(row.getBadWarehouseBin())
    ) {
      WarehouseBinSearchParamPo badWarehouseBinSearchParam =
        new WarehouseBinSearchParamPo();
      badWarehouseBinSearchParam.setLimit(2); // 最大只返回二行记录
      badWarehouseBinSearchParam.setStorageBinEq(
        SheetUtils.trim(row.getBadWarehouseBinStorageBin())
      );
      badWarehouseBinSearchParam.applySqlSegments();
      List<WarehouseBinItemVo> badWarehouseBinMatches =
        warehouseBinMapper.search(badWarehouseBinSearchParam);
      if (badWarehouseBinMatches.size() == 0) {
        ir.addError("badWarehouseBinStorageBin", "未能在仓位中找到匹配的数据");
      } else if (badWarehouseBinMatches.size() > 1) {
        ir.addError(
          "badWarehouseBinStorageBin",
          "关联不唯一，在仓位中找到多个匹配的数据"
        );
      } else {
        vo.setBadWarehouseBin(badWarehouseBinMatches.get(0).getId());
      }
    }
    // 处理关联字段“入库仓位”
    if (
      !SheetUtils.isBlank(row.getNewGoodWhbStorageBin()) &&
      SheetUtils.isBlank(row.getNewGoodWhb())
    ) {
      WarehouseBinSearchParamPo newGoodWhbSearchParam =
        new WarehouseBinSearchParamPo();
      newGoodWhbSearchParam.setLimit(2); // 最大只返回二行记录
      newGoodWhbSearchParam.setStorageBinEq(
        SheetUtils.trim(row.getNewGoodWhbStorageBin())
      );
      newGoodWhbSearchParam.applySqlSegments();
      List<WarehouseBinItemVo> newGoodWhbMatches = warehouseBinMapper.search(
        newGoodWhbSearchParam
      );
      if (newGoodWhbMatches.size() == 0) {
        ir.addError("newGoodWhbStorageBin", "未能在仓位中找到匹配的数据");
      } else if (newGoodWhbMatches.size() > 1) {
        ir.addError(
          "newGoodWhbStorageBin",
          "关联不唯一，在仓位中找到多个匹配的数据"
        );
      } else {
        vo.setNewGoodWhb(newGoodWhbMatches.get(0).getId());
      }
    }
    // 处理关联字段“新次品仓位”
    if (
      !SheetUtils.isBlank(row.getNewBadWhbStorageBin()) &&
      SheetUtils.isBlank(row.getNewBadWhb())
    ) {
      WarehouseBinSearchParamPo newBadWhbSearchParam =
        new WarehouseBinSearchParamPo();
      newBadWhbSearchParam.setLimit(2); // 最大只返回二行记录
      newBadWhbSearchParam.setStorageBinEq(
        SheetUtils.trim(row.getNewBadWhbStorageBin())
      );
      newBadWhbSearchParam.applySqlSegments();
      List<WarehouseBinItemVo> newBadWhbMatches = warehouseBinMapper.search(
        newBadWhbSearchParam
      );
      if (newBadWhbMatches.size() == 0) {
        ir.addError("newBadWhbStorageBin", "未能在仓位中找到匹配的数据");
      } else if (newBadWhbMatches.size() > 1) {
        ir.addError(
          "newBadWhbStorageBin",
          "关联不唯一，在仓位中找到多个匹配的数据"
        );
      } else {
        vo.setNewBadWhb(newBadWhbMatches.get(0).getId());
      }
    }
    // 处理关联字段“库存”
    if (
      !SheetUtils.isBlank(row.getInventoryIdId()) &&
      SheetUtils.isBlank(row.getInventoryId())
    ) {
      InventoryPlacementRSearchParamPo inventoryIdSearchParam =
        new InventoryPlacementRSearchParamPo();
      inventoryIdSearchParam.setLimit(2); // 最大只返回二行记录
      inventoryIdSearchParam.setIdEq(SheetUtils.toLong(row.getInventoryIdId()));
      inventoryIdSearchParam.applySqlSegments();
      List<InventoryPlacementRItemVo> inventoryIdMatches =
        inventoryPlacementRMapper.search(inventoryIdSearchParam);
      if (inventoryIdMatches.size() == 0) {
        ir.addError("inventoryIdId", "未能在库存货位放置表中找到匹配的数据");
      } else if (inventoryIdMatches.size() > 1) {
        ir.addError(
          "inventoryIdId",
          "关联不唯一，在库存货位放置表中找到多个匹配的数据"
        );
      } else {
        vo.setInventoryId(inventoryIdMatches.get(0).getId());
      }
    }
    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<AdjustmentOrderImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<AdjustmentOrderImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            AdjustmentOrderImportPo.class,
            AdjustmentOrderAndAdjustmentOrderProductImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              AdjustmentOrderImportPo row,
              AnalysisContext cxt
            ) {
              AdjustmentOrderVo vo = new AdjustmentOrderVo();
              ImportRow<AdjustmentOrderImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<AdjustmentOrderImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<AdjustmentOrderImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      AdjustmentOrderVo vo = new AdjustmentOrderVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"调整单号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "orderSn".equals(m.getField())
          )
      ) {
        vo.setOrderSn(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "AdjustmentOrder.orderSn")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      // 子表数据处理
      importChild(vo, row, i, variables);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  protected void importChild(
    AdjustmentOrderVo vo,
    ImportRow<AdjustmentOrderImportPo> row,
    int i,
    Map<String, Object> variables
  ) {
    if (
      row.getRow().getProductLists() == null ||
      row.getRow().getProductLists().isEmpty()
    ) {
      return;
    }
    for (ImportRow<AdjustmentOrderAndAdjustmentOrderProductImportPo> childRow : row
      .getRow()
      .getProductLists()) {
      AdjustmentOrderProductItemVo itemVo = new AdjustmentOrderProductItemVo();
      final ImportRow<AdjustmentOrderAndAdjustmentOrderProductImportPo> rowChild =
        excelToImportChildRow(
          row,
          childRow.getRow(),
          childRow.getRowNumber(),
          vo,
          itemVo,
          variables
        );
      itemVo.setId(childRow.getUpdateId());
      if (rowChild.getErrors() != null && rowChild.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            rowChild.getRowNumber(),
            rowChild.getJoinErrorMessage()
          )
        );
      }
      if (vo.getProductLists() == null) {
        vo.setProductLists(new ArrayList<>());
      }
      vo.getProductLists().add(itemVo);
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    AdjustmentOrderSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.setChildMappingOption(
        new CustomExcelExport.ChildMappingOption()
          .setFieldName("productLists")
          .setChildPageSearch((parentRecord, current, pageSize) -> {
            AdjustmentOrderItemVo parent = (AdjustmentOrderItemVo) parentRecord;
            AdjustmentOrderProductSearchParamPo searchParamPo =
              new AdjustmentOrderProductSearchParamPo();
            searchParamPo.setCurrent(current);
            searchParamPo.setPageSize(pageSize);
            searchParamPo.setParentAdjustmentOrderEq(parent.getId());
            return adjustmentOrderProductService.pageSearch(searchParamPo);
          })
      );
      exportOptions.addFieldMappingOption(
        "productLists.parentAdjustmentOrder",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              (
                (AdjustmentOrderProductItemVo) r
              ).getParentAdjustmentOrderOrderSn()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "productLists.prdName",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((AdjustmentOrderProductItemVo) r).getPrdNameName())
          )
      );
      exportOptions.addFieldMappingOption(
        "productLists.shop",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((AdjustmentOrderProductItemVo) r).getShopShopName())
          )
      );
      exportOptions.addFieldMappingOption(
        "productLists.fnsku",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((AdjustmentOrderProductItemVo) r).getFnskuFnsku())
          )
      );
      exportOptions.addFieldMappingOption(
        "productLists.newPrdName",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getNewPrdNameName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "productLists.newShop",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getNewShopShopName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "productLists.newFnsku",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getNewFnskuFnsku()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "productLists.goodWarehouseBin",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getGoodWarehouseBinStorageBin()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "productLists.badWarehouseBin",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getBadWarehouseBinStorageBin()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "productLists.newGoodWhb",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getNewGoodWhbStorageBin()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "productLists.newBadWhb",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getNewBadWhbStorageBin()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "productLists.inventoryId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((AdjustmentOrderProductItemVo) r).getInventoryIdId()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "wid",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((AdjustmentOrderItemVo) r).getWidName())
          )
      );
      exportOptions.addFieldMappingOption(
        "type",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> AdjustmentOrderTypeEnums.toLabel((String) o))
      );
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00078")
      );
      exportOptions.addStringFields(
        "formId.parentAdjustmentOrderOrderSn",
        "formId.prdNameName",
        "formId.sku",
        "formId.prdLabel",
        "formId.shopShopName",
        "formId.fnskuFnsku",
        "formId.newPrdNameName",
        "formId.newSku",
        "formId.newShopShopName",
        "formId.newFnskuFnsku",
        "formId.goodWarehouseBinStorageBin",
        "formId.badWarehouseBinStorageBin",
        "formId.newGoodWhbStorageBin",
        "formId.newBadWhbStorageBin",
        "formId.remark",
        "orderSn",
        "widName",
        "type",
        "status",
        "remark"
      );

      String fileName = String.format(
        "调整单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> statusItems = sysDictService.getDictItems("SCM00078");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<AdjustmentOrderExcelPo> items =
      new ArrayList<AdjustmentOrderExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<AdjustmentOrderItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<AdjustmentOrderItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (AdjustmentOrderItemVo item : list) {
        AdjustmentOrderExcelPo excel = new AdjustmentOrderExcelPo();
        BeanUtils.copyProperties(item, excel);
        excel.setType(AdjustmentOrderTypeEnums.toLabel(item.getType()));
        if (item.getStatus() != null) {
          statusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStatus()))
            .findFirst()
            .ifPresent(i -> excel.setStatus(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "调整单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(AdjustmentOrderExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过调整单号查询调整单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByOrderSn(String orderSn) {
    return this.baseMapper.getIdByOrderSn(orderSn);
  }

  /**
   * 通过调整单号查询调整单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByOrderSn(List<String> list) {
    return this.baseMapper.getIdsByOrderSn(list);
  }

  /**
   * 通过调整单主键查询调整单号
   */
  @Override
  public String getOrderSnById(Long id) {
    return this.baseMapper.getOrderSnById(id);
  }

  /**
   * 通过调整单主键查询调整单号列表
   */
  @Override
  public List<String> getOrderSnByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getOrderSnByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("orderSn"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 调整单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public AdjustmentOrderVo getVoById(Long id) throws Exception {
    AdjustmentOrderVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    AdjustmentOrderProductSearchParamPo productListsSearchParamPo =
      new AdjustmentOrderProductSearchParamPo();
    productListsSearchParamPo.setParentAdjustmentOrder(id);
    productListsSearchParamPo.getExtendData().put("queryMode", "sub");
    productListsSearchParamPo
      .getExtendData()
      .put("queryParent", "AdjustmentOrder");
    productListsSearchParamPo.applySqlSegments();
    vo.setProductLists(
      adjustmentOrderProductService.search(productListsSearchParamPo)
    );

    return vo;
  }

  /**
   * 分页查询调整单
   * @param search 查询条件
   * @return 调整单分页查询结果
   */
  @Override
  public Page<AdjustmentOrderItemVo> pageSearch(
    AdjustmentOrderSearchParamPo search
  ) {
    Page<AdjustmentOrderItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(AdjustmentOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(Page<AdjustmentOrderItemVo> pageResult) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<AdjustmentOrderItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    AdjustmentOrderProductSearchParamPo productListsSearchParamPo =
      new AdjustmentOrderProductSearchParamPo();
    productListsSearchParamPo.setSort(sort);
    productListsSearchParamPo.setPageSize(200);
    productListsSearchParamPo.setParentAdjustmentOrderInList(
      pageResult
        .getRecords()
        .stream()
        .map(AdjustmentOrderItemVo::getId)
        .collect(Collectors.toList())
    );

    Map<String, Page<AdjustmentOrderProductItemVoPages>> productListsMaps =
      adjustmentOrderProductService.pagesByParentAdjustmentOrder(
        productListsSearchParamPo
      );

    for (AdjustmentOrderItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put(
        "productLists",
        productListsMaps.get(itemVo.getId().toString())
      );
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 调整单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(AdjustmentOrderSearchParamPo search) {
    return appendWithChild(
      pageSearch(search),
      search.toChildSort("productLists")
    );
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    AdjustmentOrderSearchParamPo search
  ) {
    AdjustmentOrderSearchParamPo parentSearchParam =
      new AdjustmentOrderSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<AdjustmentOrderItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      AdjustmentOrderItemVo itemVo = parentList.get(0);

      AdjustmentOrderProductSearchParamPo productListsSearchParamPo =
        new AdjustmentOrderProductSearchParamPo();
      productListsSearchParamPo.setPageSize(search.getPageSize());
      productListsSearchParamPo.setCurrent(search.getCurrent());
      productListsSearchParamPo.setParentAdjustmentOrder(itemVo.getId());
      return adjustmentOrderProductService.pageSearch(
        productListsSearchParamPo
      );
    } else {
      return null;
    }
  }

  /**
   * 调整单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'AdjustmentOrderOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<AdjustmentOrderItemVo>> searchOptions(
    AdjustmentOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询调整单
   * @param search 查询条件
   * @return 调整单列表查询结果
   */
  @Override
  public List<AdjustmentOrderItemVo> search(
    AdjustmentOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询调整单最后更新时间
   * @param search 查询条件
   * @return 调整单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(AdjustmentOrderSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 确认调整
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了确认调整操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void acknowledgeAdjustment(Long id) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/AdjustmentOrder_acknowledgeAdjustment.js",
      id,
      null,
      this
    );
  }

  /**
   * 锁库存_仓位
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了锁库存_仓位操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lockpInventory(Long id) throws Exception {
    AdjustmentOrderVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareLockpInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    AdjustmentOrder updateStatusEntity = new AdjustmentOrder();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("5");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 锁库存_仓位 的参数
   */
  protected InventoryExchangeFormVo prepareLockpInventory(AdjustmentOrderVo vo)
    throws Exception {
    if (!"5".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(AdjustmentOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("调整单");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWid());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (AdjustmentOrderProductItemVo adjustmentOrderProduct : vo.getProductLists()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(adjustmentOrderProduct.getPrdName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String
            .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
      );
      exchangeItem.setShopId(
        String.valueOf(adjustmentOrderProduct.getShop()).equals("null")
          ? null
          : String.valueOf(adjustmentOrderProduct.getShop())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            adjustmentOrderProduct.getFnskuName() == null
              ? null
              : adjustmentOrderProduct.getFnskuName().trim()
          )
          ? null
          : String.valueOf(adjustmentOrderProduct.getFnskuName().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        adjustmentOrderProduct.getGoodWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
              .equals("null")
            ? "0"
            : String.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
        )
      );
      exchangeItem.setFromBinIds(binIds);
      Map<Long, Integer> toBinIds = new HashMap<>();
      toBinIds.put(
        adjustmentOrderProduct.getGoodWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
              .equals("null")
            ? "0"
            : String.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
        )
      );
      exchangeItem.setToBinIds(toBinIds);
      exchangeItem.setFromBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setToBinIdsType(TargetTypeEnum.Lock);
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(adjustmentOrderProduct.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 取消锁库存_仓位
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了取消锁库存_仓位操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void cancelLockpInventory(Long id) throws Exception {
    AdjustmentOrderVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareCancelLockpInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    AdjustmentOrder updateStatusEntity = new AdjustmentOrder();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("40");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 取消锁库存_仓位 的参数
   */
  protected InventoryExchangeFormVo prepareCancelLockpInventory(
    AdjustmentOrderVo vo
  ) throws Exception {
    if (!"40".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(AdjustmentOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("调拨单审批拒绝");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWid());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (AdjustmentOrderProductItemVo adjustmentOrderProduct : vo.getProductLists()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(adjustmentOrderProduct.getPrdName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String
            .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
      );
      exchangeItem.setShopId(
        String.valueOf(adjustmentOrderProduct.getShop()).equals("null")
          ? null
          : String.valueOf(adjustmentOrderProduct.getShop())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            adjustmentOrderProduct.getFnskuName() == null
              ? null
              : adjustmentOrderProduct.getFnskuName().trim()
          )
          ? null
          : String.valueOf(adjustmentOrderProduct.getFnskuName().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        adjustmentOrderProduct.getGoodWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
              .equals("null")
            ? "0"
            : String.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
        )
      );
      exchangeItem.setFromBinIds(binIds);
      Map<Long, Integer> toBinIds = new HashMap<>();
      toBinIds.put(
        adjustmentOrderProduct.getGoodWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
              .equals("null")
            ? "0"
            : String.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
        )
      );
      exchangeItem.setToBinIds(toBinIds);
      exchangeItem.setFromBinIdsType(TargetTypeEnum.Lock);
      exchangeItem.setToBinIdsType(TargetTypeEnum.Normal);
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(adjustmentOrderProduct.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 出库锁定
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了出库锁定操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void lockStockOut(Long id) throws Exception {
    AdjustmentOrderVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareLockStockOut(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    AdjustmentOrder updateStatusEntity = new AdjustmentOrder();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("10");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 出库锁定 的参数
   */
  protected InventoryOutboundFormVo prepareLockStockOut(AdjustmentOrderVo vo)
    throws Exception {
    if (!"10".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(AdjustmentOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Lock);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("换标出库减去锁定");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (AdjustmentOrderProductItemVo adjustmentOrderProduct : vo.getProductLists()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(adjustmentOrderProduct.getPrdName());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String
            .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
      );
      outboundItem.setShopId(
        String.valueOf(adjustmentOrderProduct.getShop()).equals("null")
          ? null
          : String.valueOf(adjustmentOrderProduct.getShop())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            adjustmentOrderProduct.getFnskuName() == null
              ? null
              : adjustmentOrderProduct.getFnskuName().trim()
          )
          ? null
          : String.valueOf(adjustmentOrderProduct.getFnskuName().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        adjustmentOrderProduct.getGoodWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
              .equals("null")
            ? "0"
            : String.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Lock);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(adjustmentOrderProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 锁库存_即时
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了锁库存_即时操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void locksInventory(Long id) throws Exception {
    AdjustmentOrderVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareLocksInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    AdjustmentOrder updateStatusEntity = new AdjustmentOrder();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("40");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 锁库存_即时 的参数
   */
  protected InventoryExchangeFormVo prepareLocksInventory(AdjustmentOrderVo vo)
    throws Exception {
    if (!"5".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(AdjustmentOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setTo(TargetTypeEnum.Lock);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("调整单");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWid());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (AdjustmentOrderProductItemVo adjustmentOrderProduct : vo.getProductLists()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(adjustmentOrderProduct.getPrdName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String
            .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
      );
      exchangeItem.setShopId(
        String.valueOf(adjustmentOrderProduct.getShop()).equals("null")
          ? null
          : String.valueOf(adjustmentOrderProduct.getShop())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            adjustmentOrderProduct.getFnskuName() == null
              ? null
              : adjustmentOrderProduct.getFnskuName().trim()
          )
          ? null
          : String.valueOf(adjustmentOrderProduct.getFnskuName().trim())
      );
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(adjustmentOrderProduct.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 取消锁库存_即时
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了取消锁库存_即时操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void cancelLocksInventory(Long id) throws Exception {
    AdjustmentOrderVo vo = getVoById(id);
    InventoryExchangeFormVo formVo = prepareCancelLocksInventory(vo);
    inventoryBusinessService.exchange(formVo);
    // 更新成功状态
    AdjustmentOrder updateStatusEntity = new AdjustmentOrder();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("5");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 取消锁库存_即时 的参数
   */
  protected InventoryExchangeFormVo prepareCancelLocksInventory(
    AdjustmentOrderVo vo
  ) throws Exception {
    if (!"40".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
    if (ReflectUtil.hasField(AdjustmentOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setFrom(TargetTypeEnum.Lock);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("取消调拨单");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("出仓库 为空");
    }
    formVo.setFromStockId(vo.getWid());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("入仓库 为空");
    }
    formVo.setToStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (AdjustmentOrderProductItemVo adjustmentOrderProduct : vo.getProductLists()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(adjustmentOrderProduct.getPrdName());
      InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
      exchangeItem.setItem(inventoryItem);
      exchangeItem.setQty(
        String
            .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
      );
      exchangeItem.setShopId(
        String.valueOf(adjustmentOrderProduct.getShop()).equals("null")
          ? null
          : String.valueOf(adjustmentOrderProduct.getShop())
      );
      exchangeItem.setFnSku(
        ObjectUtils.isEmpty(
            adjustmentOrderProduct.getFnskuName() == null
              ? null
              : adjustmentOrderProduct.getFnskuName().trim()
          )
          ? null
          : String.valueOf(adjustmentOrderProduct.getFnskuName().trim())
      );
      exchangeItem.setCustomId(vo.getId());
      exchangeItem.setCustomBdId(adjustmentOrderProduct.getId());
      formVo.add(exchangeItem);
    }
    return formVo;
  }

  /**
   * 同步数据
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了同步数据操作"
  )
  @Override
  public void syncData() throws Exception {
    if (adjustmentOrderSyncDataAction == null) {
      throw new Exception("此操作当前不可用");
    }
    adjustmentOrderSyncDataAction.run();
  }

  /**
   * 批量确认调整
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了批量确认调整操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void batchValidationAdjustment(List<Long> ids) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/AdjustmentOrder_batchValidationAdjustment.js",
      ids,
      null,
      this
    );
  }

  /**
   * 撤销
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了撤销操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void revocation(Long id) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/AdjustmentOrder_revocation.js",
      id,
      null,
      this
    );
  }

  /**
   * 正常库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了正常库存操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void good(Long id) throws Exception {
    AdjustmentOrderVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareGood(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    AdjustmentOrder updateStatusEntity = new AdjustmentOrder();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("20");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 正常库存 的参数
   */
  protected InventoryStorageFormVo prepareGood(AdjustmentOrderVo vo)
    throws Exception {
    if (!"10".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(AdjustmentOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setSupportNegative(true);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("库存调整");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    for (AdjustmentOrderProductItemVo adjustmentOrderProduct : vo.getProductLists()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(adjustmentOrderProduct.getPrdName());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String.valueOf(adjustmentOrderProduct.getGoodAdjustNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(adjustmentOrderProduct.getGoodAdjustNum())
      );
      storageItem.setShopId(
        String.valueOf(adjustmentOrderProduct.getShop()).equals("null")
          ? null
          : String.valueOf(adjustmentOrderProduct.getShop())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            adjustmentOrderProduct.getFnskuName() == null
              ? null
              : adjustmentOrderProduct.getFnskuName().trim()
          )
          ? null
          : String.valueOf(adjustmentOrderProduct.getFnskuName().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        adjustmentOrderProduct.getGoodWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(adjustmentOrderProduct.getGoodAdjustNum())
              .equals("null")
            ? "0"
            : String.valueOf(adjustmentOrderProduct.getGoodAdjustNum())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(adjustmentOrderProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 次品库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了次品库存操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void bad(Long id) throws Exception {
    AdjustmentOrderVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareBad(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    AdjustmentOrder updateStatusEntity = new AdjustmentOrder();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("10");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 次品库存 的参数
   */
  protected InventoryStorageFormVo prepareBad(AdjustmentOrderVo vo)
    throws Exception {
    if (!"10".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(AdjustmentOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setSupportNegative(true);
    formVo.setTo(TargetTypeEnum.Defect);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("库存调整");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    for (AdjustmentOrderProductItemVo adjustmentOrderProduct : vo.getProductLists()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(adjustmentOrderProduct.getPrdName());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String.valueOf(adjustmentOrderProduct.getBadAdjustNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(adjustmentOrderProduct.getBadAdjustNum())
      );
      storageItem.setShopId(
        String.valueOf(adjustmentOrderProduct.getShop()).equals("null")
          ? null
          : String.valueOf(adjustmentOrderProduct.getShop())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            adjustmentOrderProduct.getFnskuName() == null
              ? null
              : adjustmentOrderProduct.getFnskuName().trim()
          )
          ? null
          : String.valueOf(adjustmentOrderProduct.getFnskuName().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        adjustmentOrderProduct.getBadWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(adjustmentOrderProduct.getBadAdjustNum())
              .equals("null")
            ? "0"
            : String.valueOf(adjustmentOrderProduct.getBadAdjustNum())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(adjustmentOrderProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 出库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了出库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void stockOut(Long id) throws Exception {
    AdjustmentOrderVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareStockOut(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    AdjustmentOrder updateStatusEntity = new AdjustmentOrder();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("10");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 出库 的参数
   */
  protected InventoryOutboundFormVo prepareStockOut(AdjustmentOrderVo vo)
    throws Exception {
    if (!"10".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(AdjustmentOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setSupportNegative(true);
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("换标出库");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (AdjustmentOrderProductItemVo adjustmentOrderProduct : vo.getProductLists()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(adjustmentOrderProduct.getPrdName());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String
            .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
      );
      outboundItem.setShopId(
        String.valueOf(adjustmentOrderProduct.getShop()).equals("null")
          ? null
          : String.valueOf(adjustmentOrderProduct.getShop())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            adjustmentOrderProduct.getFnskuName() == null
              ? null
              : adjustmentOrderProduct.getFnskuName().trim()
          )
          ? null
          : String.valueOf(adjustmentOrderProduct.getFnskuName().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        adjustmentOrderProduct.getGoodWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
              .equals("null")
            ? "0"
            : String.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Normal);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(adjustmentOrderProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 入库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了入库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void stockIn(Long id) throws Exception {
    AdjustmentOrderVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareStockIn(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    AdjustmentOrder updateStatusEntity = new AdjustmentOrder();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("20");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 入库 的参数
   */
  protected InventoryStorageFormVo prepareStockIn(AdjustmentOrderVo vo)
    throws Exception {
    if (!"10".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(AdjustmentOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setSupportNegative(true);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("换标入库");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    for (AdjustmentOrderProductItemVo adjustmentOrderProduct : vo.getProductLists()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(adjustmentOrderProduct.getPrdName());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String
            .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
      );
      storageItem.setShopId(
        String.valueOf(adjustmentOrderProduct.getNewShop()).equals("null")
          ? null
          : String.valueOf(adjustmentOrderProduct.getNewShop())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            adjustmentOrderProduct.getNewFnskuName() == null
              ? null
              : adjustmentOrderProduct.getNewFnskuName().trim()
          )
          ? null
          : String.valueOf(adjustmentOrderProduct.getNewFnskuName().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        adjustmentOrderProduct.getNewGoodWhb(),
        Integer.parseInt(
          String
              .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
              .equals("null")
            ? "0"
            : String.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(adjustmentOrderProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 撤销正常入库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了撤销正常入库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void unGood(Long id) throws Exception {
    AdjustmentOrderVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareUnGood(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    AdjustmentOrder updateStatusEntity = new AdjustmentOrder();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("30");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 撤销正常入库 的参数
   */
  protected InventoryStorageFormVo prepareUnGood(AdjustmentOrderVo vo)
    throws Exception {
    if (!"20".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(AdjustmentOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消入库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("库存调整");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    for (AdjustmentOrderProductItemVo adjustmentOrderProduct : vo.getProductLists()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(adjustmentOrderProduct.getPrdName());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String.valueOf(adjustmentOrderProduct.getGoodAdjustNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(adjustmentOrderProduct.getGoodAdjustNum())
      );
      storageItem.setShopId(
        String.valueOf(adjustmentOrderProduct.getShop()).equals("null")
          ? null
          : String.valueOf(adjustmentOrderProduct.getShop())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            adjustmentOrderProduct.getFnskuName() == null
              ? null
              : adjustmentOrderProduct.getFnskuName().trim()
          )
          ? null
          : String.valueOf(adjustmentOrderProduct.getFnskuName().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        adjustmentOrderProduct.getGoodWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(adjustmentOrderProduct.getGoodAdjustNum())
              .equals("null")
            ? "0"
            : String.valueOf(adjustmentOrderProduct.getGoodAdjustNum())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(adjustmentOrderProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 撤销次品库存
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了撤销次品库存操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void unBad(Long id) throws Exception {
    AdjustmentOrderVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareUnBad(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    AdjustmentOrder updateStatusEntity = new AdjustmentOrder();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("20");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 撤销次品库存 的参数
   */
  protected InventoryStorageFormVo prepareUnBad(AdjustmentOrderVo vo)
    throws Exception {
    if (!"20".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(AdjustmentOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消入库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setTo(TargetTypeEnum.Defect);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("库存调整");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    for (AdjustmentOrderProductItemVo adjustmentOrderProduct : vo.getProductLists()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(adjustmentOrderProduct.getPrdName());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String.valueOf(adjustmentOrderProduct.getBadAdjustNum()).equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(adjustmentOrderProduct.getBadAdjustNum())
      );
      storageItem.setShopId(
        String.valueOf(adjustmentOrderProduct.getShop()).equals("null")
          ? null
          : String.valueOf(adjustmentOrderProduct.getShop())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            adjustmentOrderProduct.getFnskuName() == null
              ? null
              : adjustmentOrderProduct.getFnskuName().trim()
          )
          ? null
          : String.valueOf(adjustmentOrderProduct.getFnskuName().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        adjustmentOrderProduct.getBadWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(adjustmentOrderProduct.getBadAdjustNum())
              .equals("null")
            ? "0"
            : String.valueOf(adjustmentOrderProduct.getBadAdjustNum())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(adjustmentOrderProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 撤销出库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了撤销出库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void unStockOut(Long id) throws Exception {
    AdjustmentOrderVo vo = getVoById(id);
    InventoryOutboundFormVo formVo = prepareUnStockOut(vo);
    inventoryBusinessService.outbound(formVo);
    // 更新成功状态
    AdjustmentOrder updateStatusEntity = new AdjustmentOrder();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("20");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 撤销出库 的参数
   */
  protected InventoryOutboundFormVo prepareUnStockOut(AdjustmentOrderVo vo)
    throws Exception {
    if (!"20".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryOutboundFormVo formVo = new InventoryOutboundFormVo();
    if (ReflectUtil.hasField(AdjustmentOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消出库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setFrom(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("换标出库");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    formVo.setModel(PatternEnum.FIFO);
    for (AdjustmentOrderProductItemVo adjustmentOrderProduct : vo.getProductLists()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(adjustmentOrderProduct.getPrdName());
      InventoryOutboundVo outboundItem = new InventoryOutboundVo();
      outboundItem.setItem(inventoryItem);
      outboundItem.setQty(
        String
            .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
      );
      outboundItem.setShopId(
        String.valueOf(adjustmentOrderProduct.getShop()).equals("null")
          ? null
          : String.valueOf(adjustmentOrderProduct.getShop())
      );
      outboundItem.setFnSku(
        ObjectUtils.isEmpty(
            adjustmentOrderProduct.getFnskuName() == null
              ? null
              : adjustmentOrderProduct.getFnskuName().trim()
          )
          ? null
          : String.valueOf(adjustmentOrderProduct.getFnskuName().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        adjustmentOrderProduct.getGoodWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
              .equals("null")
            ? "0"
            : String.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
        )
      );
      outboundItem.setBinIds(binIds);
      outboundItem.setFromBinIdsType(TargetTypeEnum.Normal);
      outboundItem.setCustomId(vo.getId());
      outboundItem.setCustomBdId(adjustmentOrderProduct.getId());
      formVo.add(outboundItem);
    }
    return formVo;
  }

  /**
   * 撤销入库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了撤销入库操作"
  )
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void unStockIn(Long id) throws Exception {
    AdjustmentOrderVo vo = getVoById(id);
    InventoryStorageFormVo formVo = prepareUnStockIn(vo);
    inventoryBusinessService.storage(formVo);
    // 更新成功状态
    AdjustmentOrder updateStatusEntity = new AdjustmentOrder();
    updateStatusEntity.setId(id);
    updateStatusEntity.setStatus("30");
    updateById(updateStatusEntity);
  }

  /**
   * 准备用于 撤销入库 的参数
   */
  protected InventoryStorageFormVo prepareUnStockIn(AdjustmentOrderVo vo)
    throws Exception {
    if (!"20".equals(vo.getStatus())) {
      throw new Exception("当前单据状态不可进行此操作！");
    }
    InventoryStorageFormVo formVo = new InventoryStorageFormVo();
    if (ReflectUtil.hasField(AdjustmentOrderVo.class, "remark")) {
      formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
    }
    formVo.setOperate("撤消入库");
    formVo.setReverseQtySign(true);
    formVo.setSupportNegative(true);
    formVo.setTo(TargetTypeEnum.Normal);
    formVo.setFormNum(vo.getOrderSn());
    formVo.setDocumentType("换标入库");
    if (ObjectUtils.isEmpty(vo.getCreateUser())) {
      throw new Exception("关联制单人为空");
    }
    formVo.setFormOperator(vo.getCreateUser().toString());
    if (ObjectUtils.isEmpty(vo.getWid())) {
      throw new Exception("仓库 为空");
    }
    formVo.setStockId(vo.getWid());
    for (AdjustmentOrderProductItemVo adjustmentOrderProduct : vo.getProductLists()) {
      SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
      inventoryItem.setId(adjustmentOrderProduct.getPrdName());
      InventoryStorageVo storageItem = new InventoryStorageVo();
      storageItem.setItem(inventoryItem);
      storageItem.setQty(
        String
            .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
            .equals("null")
          ? BigDecimal.valueOf(0)
          : BigDecimal.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
      );
      storageItem.setShopId(
        String.valueOf(adjustmentOrderProduct.getNewShop()).equals("null")
          ? null
          : String.valueOf(adjustmentOrderProduct.getNewShop())
      );
      storageItem.setFnSku(
        ObjectUtils.isEmpty(
            adjustmentOrderProduct.getNewFnskuName() == null
              ? null
              : adjustmentOrderProduct.getNewFnskuName().trim()
          )
          ? null
          : String.valueOf(adjustmentOrderProduct.getNewFnskuName().trim())
      );
      Map<Long, Integer> binIds = new HashMap<>();
      binIds.put(
        adjustmentOrderProduct.getGoodWarehouseBin(),
        Integer.parseInt(
          String
              .valueOf(adjustmentOrderProduct.getAdjustmentAmount())
              .equals("null")
            ? "0"
            : String.valueOf(adjustmentOrderProduct.getAdjustmentAmount())
        )
      );
      storageItem.setBinIds(binIds);
      storageItem.setFromBinIdsType(TargetTypeEnum.Normal);
      storageItem.setCustomId(vo.getId());
      storageItem.setCustomBdId(adjustmentOrderProduct.getId());
      formVo.add(storageItem);
    }
    return formVo;
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    AdjustmentOrderSearchParamPo search = new AdjustmentOrderSearchParamPo();
    return MapUtil
      .builder()
      .put("VadAll", this.baseMapper.vadAllCount(search))
      .put("VadSubmit", this.baseMapper.vadSubmitCount(search))
      .put("VadApprove", this.baseMapper.vadApproveCount(search))
      .put("VadChange", this.baseMapper.vadChangeCount(search))
      .put("VadFinshed", this.baseMapper.vadFinshedCount(search))
      .put("VadRevoke", this.baseMapper.vadRevokeCount(search))
      .build();
  }

  /**
   * 全部
   */
  @Override
  public List<AdjustmentOrderItemVo> vadAll(
    AdjustmentOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.vadAll(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<AdjustmentOrderItemVo> vadAllPage(
    AdjustmentOrderSearchParamPo search
  ) {
    Page<AdjustmentOrderItemVo> vadAllPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return vadAllPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return vadAllPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    vadAllPage =
      this.baseMapper.vadAllPage(
          search.toPage(this.baseMapper.vadAllCount(search)),
          search
        );
    List<Long> recordIds = vadAllPage
      .getRecords()
      .stream()
      .map(AdjustmentOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return vadAllPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return vadAllPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    vadAllPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return vadAllPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 调整单分页查询结果
   */
  @Override
  public Page<?> vadAllPageWithChildSearch(
    AdjustmentOrderSearchParamPo search
  ) {
    return appendWithChild(
      vadAllPage(search),
      search.toChildSort("productLists")
    );
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date vadAllLastUpdateTime(AdjustmentOrderSearchParamPo search) {
    return this.baseMapper.vadAllLastUpdateTime(search);
  }

  /**
   * 待提交
   */
  @Override
  public List<AdjustmentOrderItemVo> vadSubmit(
    AdjustmentOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.vadSubmit(search);
  }

  /**
   * 待提交分页
   */
  @Override
  public Page<AdjustmentOrderItemVo> vadSubmitPage(
    AdjustmentOrderSearchParamPo search
  ) {
    Page<AdjustmentOrderItemVo> vadSubmitPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return vadSubmitPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return vadSubmitPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    vadSubmitPage =
      this.baseMapper.vadSubmitPage(
          search.toPage(this.baseMapper.vadSubmitCount(search)),
          search
        );
    List<Long> recordIds = vadSubmitPage
      .getRecords()
      .stream()
      .map(AdjustmentOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return vadSubmitPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return vadSubmitPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    vadSubmitPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return vadSubmitPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 调整单分页查询结果
   */
  @Override
  public Page<?> vadSubmitPageWithChildSearch(
    AdjustmentOrderSearchParamPo search
  ) {
    return appendWithChild(
      vadSubmitPage(search),
      search.toChildSort("productLists")
    );
  }

  /**
   * 查询待提交最后更新时间
   * @param search 查询条件
   * @return 待提交最后更新时间
   */
  @Override
  public Date vadSubmitLastUpdateTime(AdjustmentOrderSearchParamPo search) {
    return this.baseMapper.vadSubmitLastUpdateTime(search);
  }

  /**
   * 待审批
   */
  @Override
  public List<AdjustmentOrderItemVo> vadApprove(
    AdjustmentOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.vadApprove(search);
  }

  /**
   * 待审批分页
   */
  @Override
  public Page<AdjustmentOrderItemVo> vadApprovePage(
    AdjustmentOrderSearchParamPo search
  ) {
    Page<AdjustmentOrderItemVo> vadApprovePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return vadApprovePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return vadApprovePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    vadApprovePage =
      this.baseMapper.vadApprovePage(
          search.toPage(this.baseMapper.vadApproveCount(search)),
          search
        );
    List<Long> recordIds = vadApprovePage
      .getRecords()
      .stream()
      .map(AdjustmentOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return vadApprovePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return vadApprovePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    vadApprovePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return vadApprovePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 调整单分页查询结果
   */
  @Override
  public Page<?> vadApprovePageWithChildSearch(
    AdjustmentOrderSearchParamPo search
  ) {
    return appendWithChild(
      vadApprovePage(search),
      search.toChildSort("productLists")
    );
  }

  /**
   * 查询待审批最后更新时间
   * @param search 查询条件
   * @return 待审批最后更新时间
   */
  @Override
  public Date vadApproveLastUpdateTime(AdjustmentOrderSearchParamPo search) {
    return this.baseMapper.vadApproveLastUpdateTime(search);
  }

  /**
   * 待调整
   */
  @Override
  public List<AdjustmentOrderItemVo> vadChange(
    AdjustmentOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.vadChange(search);
  }

  /**
   * 待调整分页
   */
  @Override
  public Page<AdjustmentOrderItemVo> vadChangePage(
    AdjustmentOrderSearchParamPo search
  ) {
    Page<AdjustmentOrderItemVo> vadChangePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return vadChangePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return vadChangePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    vadChangePage =
      this.baseMapper.vadChangePage(
          search.toPage(this.baseMapper.vadChangeCount(search)),
          search
        );
    List<Long> recordIds = vadChangePage
      .getRecords()
      .stream()
      .map(AdjustmentOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return vadChangePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return vadChangePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    vadChangePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return vadChangePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 调整单分页查询结果
   */
  @Override
  public Page<?> vadChangePageWithChildSearch(
    AdjustmentOrderSearchParamPo search
  ) {
    return appendWithChild(
      vadChangePage(search),
      search.toChildSort("productLists")
    );
  }

  /**
   * 查询待调整最后更新时间
   * @param search 查询条件
   * @return 待调整最后更新时间
   */
  @Override
  public Date vadChangeLastUpdateTime(AdjustmentOrderSearchParamPo search) {
    return this.baseMapper.vadChangeLastUpdateTime(search);
  }

  /**
   * 已完成
   */
  @Override
  public List<AdjustmentOrderItemVo> vadFinshed(
    AdjustmentOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.vadFinshed(search);
  }

  /**
   * 已完成分页
   */
  @Override
  public Page<AdjustmentOrderItemVo> vadFinshedPage(
    AdjustmentOrderSearchParamPo search
  ) {
    Page<AdjustmentOrderItemVo> vadFinshedPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return vadFinshedPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return vadFinshedPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    vadFinshedPage =
      this.baseMapper.vadFinshedPage(
          search.toPage(this.baseMapper.vadFinshedCount(search)),
          search
        );
    List<Long> recordIds = vadFinshedPage
      .getRecords()
      .stream()
      .map(AdjustmentOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return vadFinshedPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return vadFinshedPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    vadFinshedPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return vadFinshedPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 调整单分页查询结果
   */
  @Override
  public Page<?> vadFinshedPageWithChildSearch(
    AdjustmentOrderSearchParamPo search
  ) {
    return appendWithChild(
      vadFinshedPage(search),
      search.toChildSort("productLists")
    );
  }

  /**
   * 查询已完成最后更新时间
   * @param search 查询条件
   * @return 已完成最后更新时间
   */
  @Override
  public Date vadFinshedLastUpdateTime(AdjustmentOrderSearchParamPo search) {
    return this.baseMapper.vadFinshedLastUpdateTime(search);
  }

  /**
   * 已撤销
   */
  @Override
  public List<AdjustmentOrderItemVo> vadRevoke(
    AdjustmentOrderSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.vadRevoke(search);
  }

  /**
   * 已撤销分页
   */
  @Override
  public Page<AdjustmentOrderItemVo> vadRevokePage(
    AdjustmentOrderSearchParamPo search
  ) {
    Page<AdjustmentOrderItemVo> vadRevokePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return vadRevokePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return vadRevokePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    vadRevokePage =
      this.baseMapper.vadRevokePage(
          search.toPage(this.baseMapper.vadRevokeCount(search)),
          search
        );
    List<Long> recordIds = vadRevokePage
      .getRecords()
      .stream()
      .map(AdjustmentOrderItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return vadRevokePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return vadRevokePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    vadRevokePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return vadRevokePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 调整单分页查询结果
   */
  @Override
  public Page<?> vadRevokePageWithChildSearch(
    AdjustmentOrderSearchParamPo search
  ) {
    return appendWithChild(
      vadRevokePage(search),
      search.toChildSort("productLists")
    );
  }

  /**
   * 查询已撤销最后更新时间
   * @param search 查询条件
   * @return 已撤销最后更新时间
   */
  @Override
  public Date vadRevokeLastUpdateTime(AdjustmentOrderSearchParamPo search) {
    return this.baseMapper.vadRevokeLastUpdateTime(search);
  }

  /**
   * 数量调整
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object quantityAdjustmentPeriod(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/AdjustmentOrder_QuantityAdjustmentPeriod.js",
      args,
      this
    );
  }

  /**
   * SKU调整
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object skuAdjustment(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/AdjustmentOrder_SkuAdjustment.js",
      args,
      this
    );
  }

  /**
   * 查询可用量
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object queryAvailability(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/AdjustmentOrder_QueryAvailability.js",
      args,
      this
    );
  }

  /**
   * 查询店铺
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object storeLocator(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/AdjustmentOrder_StoreLocator.js",
      args,
      this
    );
  }

  /**
   * 查询fnsku
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object queryFnsku(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/AdjustmentOrder_QueryFnsku.js",
      args,
      this
    );
  }

  /**
   * 保存新数据
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object saveNewData(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/AdjustmentOrder_SaveNewData.js",
      args,
      this
    );
  }

  /**
   * 查询可用库位
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object queryAvailableDatabase(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/AdjustmentOrder_QueryAvailableDatabase.js",
      args,
      this
    );
  }

  /**
   * 查询次品库位
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object queryDefectiveDatabase(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/AdjustmentOrder_QueryDefectiveDatabase.js",
      args,
      this
    );
  }

  /**
   * 查询库位数量
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object queryNumberDatabase(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/AdjustmentOrder_QueryNumberDatabase.js",
      args,
      this
    );
  }

  /**
   * 查询SKU
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object querySku(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/AdjustmentOrder_QuerySku.js",
      args,
      this
    );
  }

  /**
   * 筛选数据
   */
  @Override
  public Page<AdjustmentOrderDataFiltrationResult> dataFiltration(
    AdjustmentOrderDataFiltrationParam param
  ) {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    if (currentUser != null) {
      param.setCurrentUserId(currentUser.getUserId());
    }
    param.setDisableDataPremissions(true);
    return this.baseMapper.dataFiltration(param.toPage(), param);
  }
}
